﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ConsoleApp.Model.Dto;
using ConsoleApp.Model.Entity;
using ConsoleApp.Model.Option;
using Microsoft.IdentityModel.Tokens;

namespace ConsoleApp.Service;

public class DbService :IDbService
{
    AutoDingContext _ctx;
    
    public DbService(AutoDingContext ctx)
    {
        _ctx = ctx;
    }
    
    public AjaxResult ValiDateUser(UserLoginDto param, JwtOpt jwtOpt)
    {
        try
        {
            string username = param.Username;
            string password = param.Password;
            
            string dbUsername = _ctx.Configs.Where(x=>x.ConfigKey == "USERNAME").FirstOrDefault().ConfigValue;
            string dbPassword = _ctx.Configs.Where(x=>x.ConfigKey == "PASSWORD").FirstOrDefault().ConfigValue;

            if (dbUsername == username && dbPassword == password)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim("User",username)
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOpt.SecurityKey));
                var signMethod = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var tokenOpt = new JwtSecurityToken(
                    issuer: jwtOpt.Issuer,
                    audience: jwtOpt.Audience,
                    claims: claims,
                    expires: DateTime.Now.AddDays(7),
                    signingCredentials: signMethod
                );

                var tokenStr = new JwtSecurityTokenHandler().WriteToken(tokenOpt); //生成的token
                return AjaxResult.Success(tokenStr);
            }
            else
            {
                throw new Exception("验证失败");
            }

        }
        catch (Exception ex)
        {
            return AjaxResult.Error(ex.Message);
        }
    }
}